package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.CompanyImportListener;
import com.settlement.system.model.entity.SysCompany;
import com.settlement.system.model.form.CompanyForm;
import com.settlement.system.model.query.CompanyPageQuery;
import com.settlement.system.model.vo.SysCompanyImportVo;
import com.settlement.system.service.SysCompanyService;
import com.settlement.system.service.SysStoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 入账主体控制器
 */
@Tag(name = "入账主体设置接口")
@RestController
@RequestMapping("/api/v1/company")
@RequiredArgsConstructor
public class SysCompanyController {

    private final SysCompanyService companyService;
    private final SysStoreService storeService;

    @Operation(summary = "获取入账主体设置", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/getInfo/{id}")
    public Result<SysCompany> getCompany(@PathVariable Long id) {
        return Result.success(companyService.getCompany(id));
    }

    @Operation(summary = "保存入账主体设置", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:company:save')")
    @PreventDuplicateSubmit
    public Result<?> saveCompany(@Valid @RequestBody CompanyForm company) {
        return Result.success(companyService.saveCompany(company));
    }

    @Operation(summary = "获取入账主体列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/list")
    public Result<List<SysCompany>> getCompanyList() {
        return Result.success(companyService.list());
    }

    @Operation(summary = "删除入账主体", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:company:delete')")
    public Result<?> deleteCompanies(
            @Parameter(description = "入账主体ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            SysCompany company = companyService.getById(id);
            if (storeService.getByCompanyCode(company.getCode()).size() > 0) {
                return Result.failed("存在店铺关联选择的入账主体，不能删除");
            }
        }
        boolean result = companyService.deleteCompanies(ids);
        return Result.judge(result);
    }

    @Operation(summary = "入账主体分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysCompany> getStorePage(
            @ParameterObject CompanyPageQuery queryParams
    ) {
        Page<SysCompany> result = companyService.getCompanyPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "入账主体导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    @PreAuthorize("@ss.hasPerm('sys:company:import')")
    @PreventDuplicateSubmit
    public Result<?> _import(@RequestParam("file") MultipartFile file) throws Exception {
        CompanyImportListener listener = new CompanyImportListener();
        EasyExcelFactory.read(file.getInputStream(), SysCompanyImportVo.class, listener).sheet(0).doRead();
        List<SysCompanyImportVo> vos = listener.getVos();
        companyService.importCompanies(vos);
        return Result.success();
    }

    @Operation(summary = "导出入账主体", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:company:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "入账主体.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysCompanyImportVo> companyImportVos = companyService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysCompanyImportVo.class).sheet("入账主体").doWrite(companyImportVos);
    }
}
